//
//  WYSearchReusltController.m
//  CirclePush
//
//  Created by admin on 2018/5/25.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYSearchReusltController.h"
#import "WYRecommendCell.h"
@interface WYSearchReusltController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, weak) UISearchBar *searchBar;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@end

@implementation WYSearchReusltController
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadDataWithKey:self.searchTitle];
    self.searchBar.text = self.searchTitle;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
-(void)setupUI
{
    //icon_return_black
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelDidClick)];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(returnDidClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_return_black"] style:(UIBarButtonItemStyleDone) target:self action:@selector(returnDidClick)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    
    UIView *titleView = [[UIView alloc] init];
   // titleView.backgroundColor = [UIColor blackColor];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:titleView.bounds];
    [titleView addSubview:searchBar];
    self.navigationItem.titleView = titleView;
    searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    searchBar.placeholder = [NSBundle py_localizedStringForKey:PYSearchSearchPlaceholderText];
    searchBar.backgroundImage = [NSBundle py_imageNamed:@"clearImage"];
    searchBar.delegate = self;
    //searchBar.backgroundColor = [UIColor blackColor];
    self.searchBar = searchBar;
    UIImage* searchBarBg = [self GetImageWithColor:[UIColor hexStringToColor:@"#f4f4f4" alpha:1.0] andHeight:32.0f];
    //设置背景图片
    [searchBar setBackgroundImage:searchBarBg];
    //设置背景色
    [searchBar setBackgroundColor:[UIColor clearColor]];
    
     [searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYRecommendCell" bundle:nil] forCellReuseIdentifier:@"WYRecommendCell"];
}
-(void)loadDataWithKey:(NSString *)key
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    params[@"keyword"]=key;
    
    NSString *searchParm = [self convertToJsonData:params];
    
    WEAKSELF
    [WYHttpServer getMediaListWithSearchParam:searchParm WithPageNum:@"1" WithPageSize:@"10" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
           // [weakSelf.dataArray removeAllObjects];
            
            if ([WYMedia getMediaListFromJson:response[@"result"]].count) {
                [weakSelf.dataArray addObject:[WYMedia getMediaListFromJson:response[@"result"]]];
                
            }
            [weakSelf.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }
        
    }];
}
-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self loadDataWithKey:searchBar.text];
}

#pragma mark - tableview delegate / dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WYRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYRecommendCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"WYRecommendCell" owner:nil options:nil].firstObject;
    }
    WYMedia *media = self.dataArray[indexPath.section][indexPath.row];
    [cell setMedia:media];
    [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WYMediaDetailController *mdc = [[WYMediaDetailController alloc]init];
    WYMedia *media = self.dataArray[indexPath.section][indexPath.row];
    mdc.ID = media.id;
    [self.navigationController pushViewController:mdc animated:YES];
    //  NSLog(@"%ld---%ld",indexPath.section,indexPath.row);
}


-(void)returnDidClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    self.navigationItem.titleView.py_x = PYSEARCH_MARGIN * 2;
    self.navigationItem.titleView.py_y = self.view.py_width > self.view.py_height ? 3 : 7;
    self.navigationItem.titleView.py_width = self.view.py_width - 44 - self.navigationItem.titleView.py_x * 2;
    self.navigationItem.titleView.py_height = self.view.py_width > self.view.py_height ? 24 : 30;
}

-(void)cancelDidClick
{
    
}
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGFloat height = 64;
        if (kDevice_Is_iPhoneX) {
            height = 88;
        }
        CGRect frame = CGRectMake(0, height, kScreenWidth, kScreenHeight-44);
        _tableView = [[UITableView alloc] initWithFrame:frame
                                                  style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}





@end
